package org.lex.jdbc.url;

import java.util.HashMap;
import java.util.Map;

import org.lex.string.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JdbcUrlContext implements IJdbcUrlContext {
	protected final Logger log = LoggerFactory.getLogger(JdbcUrlBuilder.class);
	protected final JdbcUrlTemplate template;
	protected Map<Variable, String> map = new HashMap<Variable, String>();

	public JdbcUrlContext(JdbcUrlTemplate template) {
		this.template = template;
		for (Variable var : template.getVariables()) {
			map.put(var, "");
		}
	}

	public JdbcUrlTemplate getTemplate() {
		return template;
	}

	public void setVariableValue(Variable var, String value) {
		if (map.containsKey(var)) {
			map.put(var, value);
		} else {
			log.warn(var + " not found");
		}
	}

	public void setVariableValue(String varName, String value) {
		Variable var = this.getVariable(varName);
		if (null != var) {
			this.setVariableValue(var, value);
		} else {
			log.warn(varName + " not found");
		}
	}

	public Variable getVariable(String varName) {
		for (Variable var : template.getVariables()) {
			if (varName.equals(var.getName())) {
				return var;
			}
		}
		return null;
	}

	public String getVariableValue(Variable var) {
		String value = map.get(var);
		if (StringUtils.isNullOrTrimEmpty(value)) {
			value = var.getDefaultValue();
		}
		return value;
	}

	public String getVariableValue(String varName) {
		Variable var = this.getVariable(varName);
		if (null != var) {
			return this.getVariableValue(var);
		} else {
			return "";
		}
	}
}
